package mysql

import (
	"OJCenter/global"
	"errors"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"xorm.io/xorm"
)

type MysqlDao struct {
	Orm *xorm.Engine
}

func NewMysqlDao() (*MysqlDao, error) {

	conf := global.Conf.DaoConf.MysqlConfig
	if conf.Maxidle < 1 {
		conf.Maxidle = 5
	}

	if conf.Maxconn < 1 {
		conf.Maxconn = 5
	}

	//Xorm
	var dbDef string
	if conf.Host == "localhost" || conf.Host == "127.0.0.1" {
		dbDef = fmt.Sprintf("%s:%s@unix(%s)/%s?charset=%s", conf.Host, conf.User, conf.Socket, conf.Name, conf.Charset)
	} else {
		dbDef = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", conf.User, conf.Pass, conf.Host, conf.Port, conf.Name, conf.Charset)
	}

	orm, err := xorm.NewEngine("mysql", dbDef)
	if err != nil {
		err = errors.New(fmt.Sprintf("xorm.NewEngine(mysql, %s), error: %s", dbDef, err))
		return nil, err
	}
	if conf.Maxidle > 0 {
		orm.SetMaxIdleConns(conf.Maxidle)
	}
	if conf.Maxconn > 0 {
		orm.SetMaxOpenConns(conf.Maxconn)
	}
	if conf.Debug {
		orm.ShowSQL(true)
	}
	return &MysqlDao{Orm: orm}, nil
}

func (d *MysqlDao) DeleteInfos(table string, cond *map[string]interface{}) (int64, error) {
	if cond == nil {
		return 0, errors.New("info is nil")
	}
	affect, err := d.Orm.Table(table).Delete(cond)
	return affect, err
}

func (d *MysqlDao) UpdateInfos(table string, info *map[string]interface{}, cInfo *map[string]interface{}) (int64, error) {
	if info == nil || cInfo == nil {
		return 0, errors.New("info is nil")
	}
	affect, err := d.Orm.Table(table).Update(info, cInfo)
	return affect, err
}

func (d *MysqlDao) InsertInfos(table string, infos ...interface{}) (int64, error) {
	sum, err := d.Orm.Table(table).Insert(infos)
	if err != nil {
		return 0, err
	}
	return sum, err
}
